package cn.jg.framework.web.controller.response;

import cn.jg.framework.auth.session.ThreadLocalPage;
import cn.jg.framework.common.exception.BadRequestException;
import cn.jg.framework.common.exception.BaseException;
import cn.jg.framework.common.exception.InternalServerErrorException;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.pagehelper.PageInfo;
import lombok.Data;
import org.springframework.http.HttpStatus;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author fanfever
 * @date 2016/7/9
 */
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public class BaseResponse<T> {

	public static final String BIZ_CODE_SUCCEED = "000000";

	/**
	 * 是否成功
	 */
	protected boolean succeed = true;
	/**
	 * 响应编码
	 */
	protected int code = HttpStatus.OK.value();

	/**
	 * 业务编码
	 */
	protected String bizCode;

	/**
	 * 响应消息
	 */
	protected String message = HttpStatus.OK.name();

	/**
	 * 是否可见
	 */
	protected boolean visible;

	/**
	 * 异常
	 */
	protected BaseException exception;

	/**
	 * 分页对象
	 */
	protected Paging paging;

	/**
	 * 业务对象
	 */
	protected T data;

	@JsonProperty("extra")
	protected Map<String, ?> extraMap;

	public BaseResponse() {
		this(null);
	}

	public BaseResponse(T t) {
		this(t, BIZ_CODE_SUCCEED);
	}

	public BaseResponse(T t, String bizCode) {
		this(t, null, bizCode);
	}

	public BaseResponse(T t, Map<String, ?> extraMap) {
		this(t, extraMap, BIZ_CODE_SUCCEED);
	}

	public BaseResponse(T t, Map<String, ?> extraMap, String bizCode) {
		this.bizCode = bizCode;
		this.extraMap = extraMap;
		if (t instanceof List) {
			PageInfo<?> pageInfo = new PageInfo((List) t);
			PageInfo sourcePageInfo = ThreadLocalPage.get();
			if(!Objects.isNull(sourcePageInfo)){
				paging = new Paging(sourcePageInfo.getPageNum(), sourcePageInfo.getPageSize(), sourcePageInfo.getTotal());
			}else{
				paging = new Paging(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal());
			}
			data = t;
		} else if (t instanceof BadRequestException) {
			this.succeed = false;
			this.code = HttpStatus.BAD_REQUEST.value();
			this.bizCode = ((BadRequestException) t).getBizCode();
			this.message = ((BadRequestException) t).getMessageList().get(0);
			this.visible = true;
			this.data = null;
		} else if (t instanceof InternalServerErrorException) {
			this.succeed = false;
			this.code = HttpStatus.INTERNAL_SERVER_ERROR.value();
			this.bizCode = ((InternalServerErrorException) t).getBizCode();
			this.message = HttpStatus.INTERNAL_SERVER_ERROR.name();
			this.exception = (InternalServerErrorException) t;
			this.data = null;
		} else {
			data = t;
		}
	}

	public static <T> BaseResponse<T> ok() {
		return new BaseResponse<>();
	}

	public static <T> BaseResponse<T> ok(T body) {
		return new BaseResponse<>(body);
	}


}
